package com.cljh.controller;

import cn.hutool.core.util.StrUtil;
import com.cljh.bean.Admin;
import com.cljh.bean.Email;
import com.cljh.bean.User;
import com.cljh.config.AuthAccess;
import com.cljh.controller.page.Code;
import com.cljh.controller.page.Result;
import com.cljh.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/email")
public class EmailController {
    @Autowired
    EmailService emailService;
    @AuthAccess
    @PostMapping
    public Result login(@RequestBody Email email) {

        if (StrUtil.isBlank(email.getEmail()) && StrUtil.isBlank(email.getCode()) && StrUtil.isBlank(email.getUsername())) {
            return new Result(Code.SAVE_ERR, null, "参数错误");
        }


        Object o = emailService.loginEmail(email);
        if (o!=null){
            if (o.getClass().equals(User.class)){
                return new Result(Code.SAVE_OK,o,"user");
            }
            if (o.getClass().equals(Admin.class)){
                return new Result(Code.SAVE_OK,o,"admin");
            }
        }else {
            return new Result(Code.SAVE_ERR,null,"邮箱验证错误");
        }

        return new Result(Code.SAVE_ERR,null,"未查到信息");
    }
    @AuthAccess
    @PutMapping
    public Result passUpd(@RequestBody Email email) {

        if (StrUtil.isBlank(email.getEmail()) && StrUtil.isBlank(email.getCode()) ) {
            return new Result(Code.SAVE_ERR, null, "参数错误");
        }

        boolean update = emailService.passUpd(email);
//        if (o.getClass().equals(User.class)){
//            return new Result(Code.SAVE_OK,o,"user");
//        }
//        if (o.getClass().equals(Admin.class)){
//            return new Result(Code.SAVE_OK,o,"admin");
//        }
        String s = emailService.selectByEmailCode(email.getEmail());
        Integer code=update ? Code.UPDATE_OK:Code.UPDATE_ERR;
        String msg=update ? "密码初始化为123456，请尽快修改":"修改失败";
        String data=update ?  s : null;
        return new Result(code,data,msg);
    }
    @AuthAccess
    @GetMapping("/check/{email}/{type}")
    public Result check(@PathVariable String email, @PathVariable Integer type) {
        System.out.println(email);
        if (StrUtil.isBlank(email)) {
            return new Result(Code.SAVE_ERR, null, "参数错误");
        }
        emailService.checkEmail(email,type);

        return new Result(Code.SAVE_OK,null,"发送成功");
    }
}
